﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OZ_StocksByWarehouseInterfaceBusiness : OZInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OZ_Query;
        //获取平台所有SKU
        public OZ_ProductInfoStocksInterfaceBusiness productInfoStocks;
        //店铺ID
        public string SellerId { get; set; }
        public OZ_StocksByWarehouseInterfaceBusiness()
        {
            this.InterfaceName = "库存余额_店铺1";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OZ_Query = this.interfaceOption.Where(x => x.OperateType == "OZ_Query").First();
            //获取平台所有SKU
            productInfoStocks = new OZ_ProductInfoStocksInterfaceBusiness();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OZ_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            try
            {

                //设置请求头参数
                var key = JObject.Parse(OZ_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Client-Id", key["Client-Id"].Value<string>());
                headers.Add("Api-Key", key["Api-Key"].Value<string>());
                this.SellerId = key["Client-Id"].Value<string>();
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };

                //获取请求的数据
                //获取有库存的sku编码
                OZ_ReqDTO data = new OZ_ReqDTO();
                data.sku = new List<string>();
                var prdList = productInfoStocks.Query<ProductInfoStocks>(productInfoStocks.OZ_Query, SqlDb);
                prdList.ForEach(p =>
                {
                    var sku = p.stocks.Select(x => x.sku).ToList();
                    data.sku.AddRange(sku);
                });
                //去除重复项
                data.sku = data.sku.Distinct().ToList();
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                StocksByWarehouseDTO result = (StocksByWarehouseDTO)JsonConvert.DeserializeObject<StocksByWarehouseDTO>(queryEventArgs.ResultStr);
                if (result.result.Count >= 0)
                {
                    //店铺ID赋值
                    result.result.ForEach(x =>
                    {
                        x.SellerId = this.SellerId;
                        x.id = x.sku + x.warehouse_id + x.SellerId;
                    });
                    queryEventArgs.Success = true;
                    queryEventArgs.Rows = result.result;
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<object> QQ = await this.QueryAsync<object>(this.OZ_Query, SqlDb);
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
